<script setup lang="ts">
import { ref, watch, onMounted, nextTick, computed } from 'vue'
import type { CommentVO, CommentAddReq, CommentQueryReq, ArticleVO } from '@/types'
import { commentApi } from '@/api/comment'
import { useAuthStore } from '@/store/modules/auth'

const props = defineProps<{
  parentId: number
  articleId: number
  showReplyInput: boolean
}>()

const emit = defineEmits<{
  (e: 'reply-submitted', commentId: number): void
  (e: 'update:showReplyInput', value: boolean): void
  (e: 'collapse'): void
}>()

const replies = ref<CommentVO[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const replyContent = ref('')
const activeReplyId = ref<number | null>(null)
const replyToUser = ref<{ id: number; nickName: string } | null>(null)

// 添加加载延迟时间常量
const LOADING_DELAY = 1000 // 1秒，与评论区保持一致

// 修改 watch 监听
watch(
  () => props.showReplyInput,
  (newVal) => {
    if (!newVal) {
      // 只在关闭时重置状态
      replyContent.value = ''
      replyToUser.value = null
      activeReplyId.value = null
    }
  },
)

// 加载回复列表
const loadReplies = async (page = 1) => {
  loading.value = true
  try {
    const params: CommentQueryReq = {
      pageIndex: page,
      pageSize: pageSize.value,
      topicId: props.articleId,
      parentId: props.parentId,
      queryReply: true,
    }
    const response = await commentApi.pageQuery(params)
    if (response.data.code === 200) {
      const pageData = response.data.data
      replies.value = page === 1 ? pageData.data : [...replies.value, ...pageData.data]
      total.value = pageData.total
      currentPage.value = page
    }
  } catch (error) {
    console.error('加载回复失败:', error)
  } finally {
    loading.value = false
  }
}

// 提交回复
const submitReply = async () => {
  if (!replyContent.value.trim()) return

  try {
    const replyData: CommentAddReq = {
      topicId: props.articleId,
      commentContent: replyContent.value,
      parentId: props.parentId,
      isReview: false,
      replyUserId: replyToUser.value?.id,
    }
    const response = await commentApi.addComment(replyData)
    if (response.data.code === 200) {
      replyContent.value = ''
      if (replyToUser.value) {
        activeReplyId.value = null
        replyToUser.value = null
      } else {
        emit('update:showReplyInput', false)
      }
      await loadReplies(1)
      emit('reply-submitted', props.parentId)
    }
  } catch (error) {
    console.error('提交回复失败:', error)
  }
}

// 添加收起回复的方法
const collapseReplies = () => {
  emit('collapse')
}

// 修改加载更多方法
const loadMore = async () => {
  if (loading.value || replies.value.length >= total.value) return

  loading.value = true
  // 确保加载动画至少显示一定时间
  await new Promise((resolve) => setTimeout(resolve, LOADING_DELAY))

  const nextPage = currentPage.value + 1
  await loadReplies(nextPage)
}

// 修改取消按钮的处理方法
const handleCancel = () => {
  replyContent.value = ''
  if (replyToUser.value) {
    // 回复的回复
    activeReplyId.value = null
    replyToUser.value = null
  } else {
    // 主回复框
    emit('update:showReplyInput', false)
  }
}

// 修改回复某人的方法
const replyToSomeone = (reply: CommentVO) => {
  if (activeReplyId.value === reply.id) {
    // 关闭当前回复框
    activeReplyId.value = null
    replyToUser.value = null
    replyContent.value = ''
  } else {
    // 打开新的回复框
    activeReplyId.value = reply.id
    replyToUser.value = {
      id: reply.userId,
      nickName: reply.userNickName,
    }
    // 确保主回复框关闭
    emit('update:showReplyInput', false)
  }
}

// 添加 onMounted 子来加载初始数据
onMounted(() => {
  console.log('CommentReply mounted:', {
    parentId: props.parentId,
    showReplyInput: props.showReplyInput,
  })
  loadReplies()
})

// 添加回复输入框的显示逻辑
const showMainReplyInput = computed(() => {
  return props.showReplyInput && !replyToUser.value
})

const showReplyToUserInput = computed(() => {
  return (reply: CommentVO) => {
    return activeReplyId.value === reply.id
  }
})

// 处理头像加载失败
const handleAvatarError = (e: Event) => {
  const target = e.target as HTMLImageElement
  if (target) {
    target.src =
      ''
    target.classList.add('bg-gray-100')
  }
}

// 获取 auth store 实例
const authStore = useAuthStore()
</script>

<template>
  <div class="ml-6">
    <!-- 评论的回复输入框 -->
    <div v-if="showMainReplyInput" class="mb-4 bg-gray-50 rounded-lg p-4">
      <textarea
        v-model="replyContent"
        rows="2"
        class="w-full px-4 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none bg-white"
        placeholder="写下你的评论..."
      ></textarea>
      <div class="mt-3 flex justify-end space-x-2">
        <button
          @click="handleCancel"
          class="px-4 py-1.5 text-sm text-gray-600 hover:text-gray-700 transition-colors duration-300"
        >
          取消
        </button>
        <button
          @click="submitReply"
          class="px-4 py-1.5 text-sm bg-blue-600 text-white rounded-full hover:bg-blue-700 transition-colors duration-300"
        >
          发送
        </button>
      </div>
    </div>

    <!-- 回复列表和回复的回复输入框 -->
    <div v-if="replies.length > 0" class="space-y-4">
      <div v-for="reply in replies" :key="reply.id">
        <div class="flex items-start space-x-3">
          <img
            :src="reply.userAvatar"
            :alt="reply.userNickName"
            class="w-8 h-8 rounded-full object-cover border-2 border-gray-100"
            @error="handleAvatarError"
          />
          <div class="flex-1 min-w-0">
            <div class="flex items-center justify-between mb-1">
              <div class="flex items-center text-sm">
                <span class="text-gray-600">{{ reply.userNickName }}</span>
                <template v-if="reply.replyUserNickName">
                  <span class="text-gray-400 mx-1">回复</span>
                  <span class="text-gray-600">@{{ reply.replyUserNickName }}</span>
                </template>
              </div>
              <span class="text-xs text-gray-500">{{ reply.createTime }}</span>
            </div>
            <p class="text-base text-gray-800 leading-relaxed mb-3 whitespace-pre-wrap">
              {{ reply.commentContent }}
            </p>
            <!-- 修改回复按钮位置 -->
            <div class="flex items-center justify-end text-sm">
              <button
                v-if="authStore.user"
                @click="() => replyToSomeone(reply)"
                class="text-gray-500 hover:text-gray-700 transition-colors"
              >
                回复
              </button>
            </div>
          </div>
        </div>

        <!-- 回复的回复输入框 -->
        <div
          v-if="showReplyToUserInput(reply)"
          class="mt-3 ml-11 bg-white rounded-lg p-3 border border-gray-100"
        >
          <div class="text-sm text-gray-600 mb-2">回复 @{{ replyToUser?.nickName }}：</div>
          <textarea
            v-model="replyContent"
            rows="2"
            class="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none"
            placeholder="写下你的回复..."
          ></textarea>
          <div class="mt-2 flex justify-end space-x-2">
            <button
              @click="handleCancel"
              class="px-3 py-1 text-sm text-gray-600 hover:text-gray-700 transition-colors duration-300"
            >
              取消
            </button>
            <button
              @click="submitReply"
              class="px-3 py-1 text-sm bg-blue-600 text-white rounded-full hover:bg-blue-700 transition-colors duration-300"
            >
              发送
            </button>
          </div>
        </div>
      </div>

      <!-- 加载更多按钮 -->
      <div v-if="replies.length < total" class="text-center py-3">
        <button
          @click="loadMore"
          class="text-sm text-blue-600 hover:text-blue-700 transition-colors duration-300"
          :disabled="loading"
        >
          <div v-if="loading" class="flex items-center justify-center space-x-2">
            <svg
              class="animate-spin h-5 w-5"
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
            >
              <circle
                class="opacity-25"
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                stroke-width="4"
              ></circle>
              <path
                class="opacity-75"
                fill="currentColor"
                d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
              ></path>
            </svg>
            <span>正在玩命加载</span>
            <span class="loading-dots"></span>
          </div>
          <span v-else>加载更多回复</span>
        </button>
      </div>
    </div>

    <!-- 收起按钮 -->
    <div class="text-center mt-4">
      <button
        @click="collapseReplies"
        class="text-sm text-gray-500 hover:text-gray-700 transition-colors duration-300 flex items-center justify-center space-x-1 mx-auto"
      >
        <span>收起回复</span>
        <svg
          xmlns="http://www.w3.org/2000/svg"
          class="h-4 w-4"
          viewBox="0 0 20 20"
          fill="currentColor"
        >
          <path
            fill-rule="evenodd"
            d="M14.707 12.707a1 1 0 01-1.414 0L10 9.414l-3.293 3.293a1 1 0 01-1.414-1.414l4-4a1 1 0 011.414 0l4 4a1 1 0 010 1.414z"
            clip-rule="evenodd"
          />
        </svg>
      </button>
    </div>
  </div>
</template>

<style scoped>
@keyframes dotsAnimation {
  0% {
    content: '.';
  }
  33% {
    content: '..';
  }
  66% {
    content: '...';
  }
  100% {
    content: '';
  }
}

.loading-dots {
  display: inline-block;
  min-width: 1.5em;
}

.loading-dots::after {
  content: '';
  animation: dotsAnimation 1s infinite steps(4);
}

.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
